import Moudle.Item;
import com.alibaba.fastjson.JSON;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Test {

    static final String FILEPATH = "D:\\测试临时文件\\新增高管\\src\\新增高管_3.xlsx";
    static Map<String, String> header_map;

    static {
        header_map = new HashMap<>();
        header_map.put("cookie", "UM_distinctid=177186af68e157-0436589dc73a-31346d-1fa400-177186af68f9a4; zg_did=%7B%22did%22%3A%20%22177186af697eab-0c04cb60bb46df-31346d-1fa400-177186af6984ef%22%7D; _uab_collina=161102239936148342628101; QCCSESSID=u5fs8haknt9a38o997mkdsls86; CNZZDATA1254842228=501952355-1611019930-https%253A%252F%252Fwww.baidu.com%252F%7C1625452408; zg_de1d1a35bfa24ce29bbf2c7eb17e6c4f=%7B%22sid%22%3A%201625455617586%2C%22updated%22%3A%201625456122514%2C%22info%22%3A%201625102119821%2C%22superProperty%22%3A%20%22%7B%5C%22%E5%BA%94%E7%94%A8%E5%90%8D%E7%A7%B0%5C%22%3A%20%5C%22%E4%BC%81%E6%9F%A5%E6%9F%A5%E7%BD%91%E7%AB%99%5C%22%7D%22%2C%22platform%22%3A%20%22%7B%7D%22%2C%22utm%22%3A%20%22%7B%7D%22%2C%22referrerDomain%22%3A%20%22%22%2C%22cuid%22%3A%20%22undefined%22%2C%22zs%22%3A%200%2C%22sc%22%3A%200%7D");
    }

    public static void main(String[] args) throws IOException, InvalidFormatException {
        /**
         * 读取excel （现任（常住地）） 数据
         * 放到企查查上查询
         * 取第一个搜索结果的地址
         * 放到高德 所搜其省份地址
         */
        Workbook workbook = WorkbookFactory.create(new File(FILEPATH));
        Sheet sheet = workbook.getSheetAt(1);

        int rowSize = sheet.getPhysicalNumberOfRows();
        for (int i = 2; i < rowSize; i++) {
            Row row = sheet.getRow(i);

            if (!(row.getCell(25)+"").equals("null")){
                continue;
            }

            boolean isFind = false;

            String keyWords = row.getCell(24) + "";
            if (keyWords.equals("") || keyWords.contains("退休") || keyWords.contains("N/A"))
                continue;

            String[] strings = keyWords.split(";");
            List<String> final_list = new ArrayList<>();

            for (int index = 0; !isFind && index < strings.length; index++) {
                /**
                 * 取数据 搜索省份信息
                 */
                try {
                    Item item = GaoDeSelectKeyWords(strings[index]);
                    if (item != null) {
                        isFind = true;
                        System.out.println(item.excel_name + " " + item.qiChaCha_name + " " + item.qiChaCha_address + " " + item.province);
                        row.createCell(25).setCellValue(item.province);

                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    System.out.println(keyWords);
                }
            }



            /**
             * 判断常住地中是否有数据
             * 没有的话 判断是否为学校
             */
            for (int index = 0; !isFind && index < strings.length; index++) {
                //Matcher matcher = Pattern.compile("(现任|现担任|目前担任|目前任|现为|至今|迄今|现就职).*?(大学|科学院|事务所|集团|公司|委员会)").matcher(strings[index]);
                Matcher matcher = getMatcher(strings[index]);
                if (matcher != null) {
                    isFind = true;
                    String resStr = matcher.group();
                    resStr = resStr.substring(matcher.group(1).length()).replaceAll(",", "");
                    try {
                        Item item = GaoDeSelectKeyWords(resStr);
                        if (item != null) {
                            isFind = true;
                            System.out.println(item.excel_name + " " + item.qiChaCha_name + " " + item.qiChaCha_address + " " + item.province);
                            row.createCell(25).setCellValue(item.province);

                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        System.out.println(keyWords);
                    }
                }
            }

//            for (int index = 0; !isFind && index < strings.length; index++) {
//                Matcher matcher = Pattern.compile("(现任|现担任|目前担任|目前任|现为|至今|迄今|现就职).*?学院").matcher(strings[index]);
//                if (matcher.find()) {
//                    isFind = true;
//                    String resStr = matcher.group();
//                    resStr = resStr.substring(matcher.group(1).length()).replaceAll(",", "");
//                    try {
//                        Item item = selectKeyWords(resStr);
//                        if (item != null) {
//                            isFind = true;
//                            System.out.println(item.excel_name + " " + item.qiChaCha_name + " " + item.qiChaCha_address);
//                            row.createCell(23).setCellValue(item.province);
//                            row.createCell(24).setCellValue(item.qiChaCha_name);
//                            row.createCell(25).setCellValue(item.qiChaCha_address);
//                        }
//                    } catch (Exception e) {
//                        e.printStackTrace();
//                        System.out.println(keyWords);
//                    }
//                }
//            }

        }

        workbook.write(new FileOutputStream("D:\\测试临时文件\\新增高管\\常住地提取\\新增高管.xlsx"));
    }

    public static Item selectKeyWords(String keyWords) throws InterruptedException {
        /**
         * 企查查中搜索信息
         * 取第一条搜索结果的地址
         */
        String qiChaChaUrl = "https://www.qcc.com/web/search?key=" + keyWords;
        Document qiChaChaDoc = Jsoup.parse(HttpConnect.HttpGet_OkHttp(qiChaChaUrl, header_map));
        String qiChaCha_address = qiChaChaDoc.select(".val.long-text").get(0).text();
        String qiChaCha_name = qiChaChaDoc.select(".maininfo").get(0).select(".title").text();

        Thread.sleep(2000);
        /**
         * 把企查查中获取的地址 放到高德进行搜索 获得省份信息
         */
        String GaoDeUrl = "https://restapi.amap.com/v3/place/text?key=1e647715410286faa0a7b2ad93086a38&keywords=" + qiChaCha_address;
        String province = JSON.parseObject(HttpConnect.HttpGet_OkHttp(GaoDeUrl)).getJSONArray("pois").getJSONObject(0).getString("pname");
        return new Item(keyWords, qiChaCha_name, qiChaCha_address, province);
        // return null;
    }

    public static Item GaoDeSelectKeyWords(String keyWords) throws InterruptedException {

        /**
         * 把企查查中获取的地址 放到高德进行搜索 获得省份信息
         */
        String GaoDeUrl = "https://restapi.amap.com/v3/place/text?key=1e647715410286faa0a7b2ad93086a38&keywords=" + keyWords;
        String province = JSON.parseObject(HttpConnect.HttpGet_OkHttp(GaoDeUrl)).getJSONArray("pois").getJSONObject(0).getString("pname");
        return new Item(keyWords, "", "", province);
        // return null;
    }

    public static Matcher getMatcher(String input){
        String[] pattern_suffix = {"大学", "公司", "事务所", "委员会", "集团", "学院", "协会"};
        for (String suffix : pattern_suffix){
            Matcher matcher = Pattern.compile("(现任|现担任|目前担任|目前任|现为|至今|迄今|现就职).*?"+suffix).matcher(input);
            if (matcher.find())
                return matcher;
        }
        return null;
    }
}


